#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ebooklib
from ebooklib import epub

import sys
from HTMLParser import HTMLParser


def convert(epub_path, txt_path):
    book = epub.read_epub(epub_path)

    f = open(txt_path, "wb")
    for doc in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):
        html = doc.get_body_content().strip()
        html = html.strip("\n")
        result = []
        parser = HTMLParser()
        parser.handle_data = result.append
        parser.feed(html)
        parser.close()

        f.write("".join(result))

    f.close()


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print "Usage: {} epub [txt]".format(sys.argv[0])
        sys.exit()

    epub_path = sys.argv[1]
    if len(sys.argv) > 2:
        txt_path = sys.argv[2]
    else:
        if epub_path.endswith(".epub"):
            txt_path = epub_path[:-5] + ".txt"
        else:
            txt_path = epub_path + ".txt"


    convert(epub_path, txt_path)

